﻿//-----------------------------------------------------------------------
// <copyright file="IMAddressFactory.cs" company="Microsoft">
//     Copyright (c) Microsoft Corporation.  All rights reserved.
// </copyright>
//-----------------------------------------------------------------------

namespace Microsoft.Live.Messenger
{
    using System;
    using System.Collections.Generic;

    internal sealed class IMAddressFactory
    {
        private readonly Dictionary<string, IMAddress> addresses = new Dictionary<string, IMAddress>(100);
        private readonly User user;

        public IMAddressFactory(User user)
        {
            this.user = user;
        }

        public IMAddress FindOrCreate(object obj)
        {
            if (obj == null)
            {
                return null;
            }

            return FindOrCreate(new MessengerEntity(obj));
        }

        public IMAddress FindOrCreate(MessengerEntity entity)
        {
            string address = entity.GetProperty<string>("Address");
            IMAddressType type = entity.GetEnumProperty<IMAddressType>("Type");

            string key = address + ":" + Convert.ToInt32(type).ToString();

            IMAddress value = null;

            if (!this.addresses.TryGetValue(key, out value))
            {
                value = new IMAddress(entity, this.user);

                this.addresses.Add(key, value);
            }

            return value;
        }
    }
}